package net.yeah.mickey_zhouyou.module.booklist.util;

import net.yeah.mickey_zhouyou.database.DBUI;
import net.yeah.mickey_zhouyou.module.booklist.domain.Book;

public class BookList {
	private static Book first;
	private static Book last;

	public static void push_front(Book book) {
		if (first == null && last == null)
			saveFirstBook(book);

		if (book != first) {
			breakFromList(book);

			book.setNextId(first.getId());
			first.setPreId(book.getId());
			DBUI.save(first);
			DBUI.save(book);
		}
	}

	public static void push_back(Book book) {
		if (first == null && last == null)
			saveFirstBook(book);

		if (book != last) {
			breakFromList(book);

			book.setPreId(last.getId());
			last.setNextId(book.getId());
			DBUI.save(last);
			DBUI.save(book);
		}
	}

	public static void insertPre(Book pre, Book book) {
		if (pre != null && book != null) {
			breakFromList(pre);
			if (book == first) {
				push_front(pre);
			} else {
				Book p = DBUI.load(Book.class, book.getPreId());
				p.setNextId(pre.getId());
				book.setPreId(pre.getId());
				pre.setPreId(p.getId());
				pre.setNextId(book.getId());
				DBUI.save(p);
				DBUI.save(pre);
				DBUI.save(book);
			}
		}
	}

	public static void insertNext(Book next, Book book) {
		if (next != null && book != null) {
			breakFromList(next);
			if (book == last) {
				push_back(next);
			} else {
				Book n = DBUI.load(Book.class, book.getNextId());
				n.setPreId(next.getId());
				book.setNextId(next.getId());
				next.setPreId(book.getId());
				next.setNextId(n.getId());
				DBUI.save(n);
				DBUI.save(next);
				DBUI.save(book);
			}
		}
	}

	private static void saveFirstBook(Book b) {
		if (b != null) {
			DBUI.save(b);
			first = b;
			last = b;
		}
	}

	private static void breakFromList(Book b) {
		if (b != null && first != null && last != null) {
			if (b == first) {
				Book f = DBUI.load(Book.class, b.getNextId());
				f.setPreId(null);
				DBUI.save(f);
				first = f;
			} else if (b == last) {
				Book l = DBUI.load(Book.class, b.getPreId());
				l.setNextId(null);
				DBUI.save(l);
				last = l;
			} else if (b.getNextId() != null && b.getPreId() != null) {
				Book pb = DBUI.load(Book.class, b.getPreId());
				Book nb = DBUI.load(Book.class, b.getNextId());
				pb.setNextId(nb.getId());
				nb.setPreId(pb.getId());
				DBUI.save(pb);
				DBUI.save(nb);
			}
			b.setPreId(null);
			b.setNextId(null);
		}
	}
}
